package cn.itrip.trade.service.impl;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.beans.pojo.ItripHotelTempStore;
import cn.itrip.common.DtoUtils;
import cn.itrip.dao.mapper.ItripHotelOrderMapper;
import cn.itrip.dao.mapper.ItripHotelTempStoreMapper;
import cn.itrip.dao.mapper.ItripTradeEndsMapper;
import cn.itrip.trade.config.WXPayConstants;
import cn.itrip.trade.config.WXPayRequest;
import cn.itrip.trade.config.WXPayUtil;
import cn.itrip.trade.service.ItripHotelOrderPayService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ItripHotelOrdePayrServiceimpl implements ItripHotelOrderPayService {

    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;

    @Resource
    private ItripTradeEndsMapper itripTradeEndsMapper;
    @Resource
    private ItripHotelTempStoreMapper itripHotelTempStoreMapper;


    /**
     *     //用户支付返回网址页面生成二维码
     * @param orderNo 订单编号
     * @return 网址
     */
    @Override
    public Dto updateOrderByorderNo(String orderNo) {
        try {
            //查询订单根据订单号
            ItripHotelOrder itripHotelOrder= itripHotelOrderMapper.selectByOrderNo(orderNo);
            if (itripHotelOrder!=null){
                Map<String,String> map=new HashMap<String,String>();
                //公众账号ID
                map.put("appid","wxab8acb865bb1637e");
                //商户号
                map.put("mch_id","11473623");
                //随机字符串
                map.put("nonce_str", WXPayUtil.generateNonceStr());
               //商品描述
                map.put("body","付款中心-订单付款");
                //商户订单号
                map.put("out_trade_no",itripHotelOrder.getOrderNo());
                //商品id
                map.put("product_id", itripHotelOrder.getId()+"");
                //标价金额
                map.put("total_fee","1");
                //终端IP
                map.put("spbill_create_ip","123.12.12.123");
                //签名类型
                map.put("sign_type","HMAC-SHA256");
                //通知地址
                map.put("notify_url","http://9ay3dt.natappfree.cc/trade/api/jieguo");
                //交易类型
                map.put("trade_type","NATIVE");
                //货币类型
                map.put("fee_type", "CNY");

                //签名
                map.put("sign",WXPayUtil.generateSignature(map,"2ab9071b06b9f739b950ddb41db2690d", WXPayConstants.SignType.HMACSHA256));
                // map变成xml 字符串
                String xml= WXPayUtil.mapToXml(map);
                //发送数据给微信息,获取结果xml
                String url="https://api.mch.weixin.qq.com/pay/unifiedorder";
                String result= WXPayRequest.sendMessageToWx(url,xml);
                Map<String,String> resultMap=  WXPayUtil.xmlToMap(result);
                //FAIL
                String  s= resultMap.get("err_code");
                if (s!=null&&s.equals("INVALID_REQUEST")){
                    return DtoUtils.getDto("2222","订单重复", null,"false",null);
                }
                if (s!=null&&s.equals("ORDERPAID")){
                    return DtoUtils.getDto("2222","订单已支付", null,"false",null);
                }
                // 4 将二维码的地址给前端  ,由前端生成二维码图片 code_url
                Map<String,String> map1=new HashMap<String,String>();
                map1.put("codeUrl",resultMap.get("code_url"));
                return DtoUtils.getDto("0000","跳转微信支付成功", map1,"true",null);
            }else{
                return DtoUtils.getDto("1111","订单信息没有", null,"false",null);
            }
        }catch (Exception e){
            return DtoUtils.getDto("2222","支付异常", null,"false",e);
        }
    }

    /**
     * 微信回调函数
     * @param xmlResult
     * @return
     */
    @Override
    public boolean huidiao(String xmlResult) throws Exception {


            Map<String,String> result= WXPayUtil.xmlToMap(xmlResult);
            if(result.get("result_code").equals("SUCCESS")&&result.get("return_code").equals("SUCCESS")){
                //out_trade_no
                //查询订单根据订单号
                ItripHotelOrder itripHotelOrder= itripHotelOrderMapper.selectByOrderNo(result.get("out_trade_no"));
                long hotelId=itripHotelOrder.getHotelId();
                long roomId=itripHotelOrder.getRoomId();
                //判断是否数据
                if (itripHotelOrder!=null){
                    //数据库增加一条消费信息信息数据库只有三个字段 把订单编号给进去 其他两个写死  数据库这张表要做自增处理
                    itripTradeEndsMapper.insert(result.get("out_trade_no"));
                    //查询库存表是否已有数据会返回多条数据用list
                    List<ItripHotelTempStore> list = itripHotelTempStoreMapper.selectByPrimaryKey(hotelId,roomId);
                    //构建数据 数据库需要增加一条数据再修改全部库存数量字段
                    ItripHotelTempStore itripHotelTempStore1=new ItripHotelTempStore();
                    itripHotelTempStore1.setHotelId(hotelId);
                    itripHotelTempStore1.setRoomId(roomId);
                    int num=0;
                    //判断库存表是否已有数据
                    if (list.size()==0){
                        //构建数据根据上面判断插入不同的数据
                        itripHotelTempStore1.setStore(20);
                        itripHotelTempStore1.setRecordDate(new Date());
                        itripHotelTempStore1.setCreationDate(new Date());
                        //没有 增加一条数据
                        num= itripHotelTempStoreMapper.insert(itripHotelTempStore1);
                    }else{
                        //构建数据根据上面判断插入不同的数据
                        itripHotelTempStore1.setStore(list.get(0).getStore());
                        itripHotelTempStore1.setCreationDate(list.get(0).getCreationDate());
                        //原来有再加一条库存信息
                        itripHotelTempStore1.setRecordDate(new Date());
                        num=itripHotelTempStoreMapper.insert(itripHotelTempStore1);
                    }
                    //判断是否添加成功
                    if (num>0){
                        //修改库存数量-1
                        itripHotelTempStoreMapper.updatestoreByid(hotelId);
                        //修改订单状态=2
                        itripHotelOrderMapper.updateByPrimaryKey(itripHotelOrder);
                        return true;
                    }
                    return  false;
                }
                return false;
            }else{
                return  false;
            }


    }

    /**
     * 页面响应方法
     * @param orderNo
     * @return
     */
    @Override
    public Dto RenderResponse(String orderNo) {
        try {
            //根据订单编号查询订单状态返回给它页面根据状态是否等于2相应的做处理
            ItripHotelOrder itripHotelOrder=  itripHotelOrderMapper.selectByOrderNo(orderNo);
            if (itripHotelOrder!=null){

                return  DtoUtils.getSuccesDto(itripHotelOrder);
            }else{
                return DtoUtils.getSuccesDto(null);
            }
        }catch (Exception e){
            return DtoUtils.getSuccesDto(null);
        }
    }


}
